package com.ruoyi.system.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IMiniappService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.file.Paths;
import java.util.Objects;

import static com.ruoyi.common.utils.WechatMiniProgramQRCode.*;


@Service
public class MiniappServiceImpl implements IMiniappService {

    private static final Logger log = LoggerFactory.getLogger(MiniappServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;


    @Override
    public boolean CreateQRcode(String orderNo,String serverUrl) {

        try {
            log.info(orderNo, serverUrl);
            generateQrcode(orderNo, serverUrl);
            return  true;

        } catch (Exception e) {
            log.error("生成说明书二维码失败2", e);
            return false;
        }

    }

    //通过orderNo判断是哪个推广渠道，如果是
    public  void generateQrcode(String  orderNo,String serverUrl) throws JsonProcessingException, UnsupportedEncodingException {
        String  modelId="45803";
        String[] parts = orderNo.split( "-");
        String firstPart = parts[0];
        String param="&reseller_id=57&order_id="+firstPart;
        //判断订单归属
        String url="https://jz.shunbo.site/reseller/info/get_order_reseller_info";
        //aString param="&reseller_id=57&order_id="+orderNo;
        log.info(url, param);
        String result= HttpUtils.sendGet(url,param);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(result);
        String code=jsonNode.get("code").toString();
        log.info(orderNo,code);
        if(Objects.equals(code, "200")){
            //设置小程序码参数
            String page="pages/qrcode/qrcode";
            String scene="type=block&modelId=" +modelId;
            String qrName="mpqr_" + modelId+".png";
            String filePath = RuoYiConfig.getUploadPath();
            String qrPath = StringUtils.format("{}/{}", DateUtils.datePath(), qrName);
            File qrFile = Paths.get(filePath, qrPath).toFile();
            String savePath=filePath+"/"+qrPath;

            log.info(savePath);
            try {
                File parentDir = qrFile.getParentFile();
                if (!parentDir.exists()) {
                    parentDir.mkdirs();
                }

                // 1. 获取Access Token
                String accessToken = getAccessToken();
                log.info(accessToken);
                // 2. 生成原始小程序码（二进制数据）
                byte[] qrCodeBytes = generateQRCode(accessToken, scene, page, 430);
                // 3. 添加订单号并保存

                addOrderNumberToImage(qrCodeBytes, orderNo, savePath);

                //4. 替换qrcode
                String qrUrl = serverUrl + FileUploadUtils.getPathFileName(filePath, qrPath);
                log.info(qrUrl);
                Long uid= new Long(2);
                SysUser user=userMapper.selectUserById(uid);
                user.setRemark(qrUrl);
                userMapper.updateUser(user);

            } catch (Exception e) {
                log.error("生成说明书二维码失败3", e);
                throw new ServiceException("生成说明书二维码失败3");
            }

        }

    }
}
